<!-- 表格组件 -->
<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-form :model="queryParams" size="small" :inline="true">
      <el-form-item>
        <el-input v-model="queryParams.name" placeholder="请输入名称" style="width: 150px" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="onSubmit">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="clear">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 按钮 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-if="checkPermission(['edu-admin', 'admin','dean-admin'])"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd()"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="dialogVisible = true"
        >批量删除</el-button>
      </el-col> -->
    </el-row>

    <el-dialog ref="form" :title="title" :visible.sync="dialogVisible" width="30%" @close="cancel">
      <el-form ref="form" :model="docu" :rules="rules" label-width="80px" size="mini">
        <el-form-item docu="name" label="名称" prop="name">
          <el-input v-model="docu.name" :disabled="docu.status == '1'" placeholder="请输入名称" style="width: 250px" />
        </el-form-item>
        <el-form-item prop="description" label="描述">
          <el-input v-model="docu.description" placeholder="请输入描述" style="width: 250px" />
        </el-form-item>
        <el-form-item label="专业" prop="deptId">
          <treeselect v-model="form.majorId" :options="deptOptions" :show-count="true" placeholder="请选择专业" style="width: 250px" />
        </el-form-item>
        <el-form-item label="教师" prop="deptId">
          <treeselect v-model="form.majorId" :options="deptOptions" :show-count="true" placeholder="请选择教师" style="width: 250px" />
        </el-form-item>
        <el-form-item>
          <span slot="label">
            <span style="color: red;">* </span>
            <el-tooltip content="将所有附件打包成一个压缩包" placement="top">
              <i class="el-icon-question" />
            </el-tooltip>
            附件
          </span>
          <el-upload
            ref="upload"
            class="upload-demo"
            :action="upload.url"
            :on-change="uploadChange"
            :file-list="fileList"
            :headers="upload.headers"
            :auto-upload="true"
            limit="1"
            :on-exceed="handleExceed"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
          >
            <el-button size="mini" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item style="margin-left: 15%">
          <el-button type="primary" @click="add">提交</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 表格 -->
    <el-table v-loading="loading" :data="tableData" @selection-change="handleSelectionChange">
      <!-- <el-table-column type="selection" width="" align="center" /> -->
      <el-table-column prop="name" label="名称" align="center" />
      <el-table-column prop="description" label="描述" align="center" />
      <el-table-column prop="majorId" label="专业" align="center" />
      <el-table-column prop="createTime" label="创建时间" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime ? parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}") : '' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.updateTime ? parseTime(scope.row.updateTime, "{y}-{m}-{d} {h}:{i}") : '' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="250" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="checkPermission(['edu-admin', 'admin','dean-admin'])"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row.id)"
          >修改</el-button>
          <el-button
            v-if="checkPermission(['edu-admin', 'admin','dean-admin'])"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="deleteById(scope.row.id)"
          >删除</el-button>
          <el-button
            v-if="checkPermission(['edu-admin', 'user', 'admin','dean-admin'])"
            size="mini"
            type="text"
            icon="el-icon-finished"
            @click="handleExport(scope.row)"
          >下载</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--分页工具条-->
    <el-pagination
      :background="background"
      :current-page="current"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="totalCount"
      style="margin-top: 8px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script>
import { page, update, deleteById, add, queryById } from '@/api/docu_induce.js'
import checkPermission from '@/utils/permission' // 权限判断函数
import { getToken } from '@/utils/auth'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { deptTreeSelect } from '@/api/user'
export default {
  components: { Treeselect },
  props: {
    user: {
      type: Object,
      default: () => ({}) // 设置一个空对象作为默认值
    }
  },
  data() {
    return {
      deptOptions: undefined,
      form: {},
      background: true,
      loading: false,
      // 每页显示的条数
      pageSize: 10,
      // 总记录数
      totalCount: 100,
      // 当前页码
      current: 1,
      // 表单校验
      rules: {
        name: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ],
        fileList: [
          { required: true, message: '不能为空', trigger: 'blur' }
        ]
      },
      // 添加数据对话框是否展示的标记
      dialogVisible: false,
      queryParams: {
        name: ''
      },
      entryDate: [], // 用于v-model绑定日期选择器的值
      value: {},
      title: '',
      docu: {
        name: '',
        majorId: '',
        fileUrl: '',
        description: '',
        fileName: ''
      },
      majorData: {
        id: '',
        label: ''
      },
      majorList: [],
      fileList: [],
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { token: getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/common/upload'
      },
      createTime: '',
      endTime: '',
      // 被选中的id数组
      selectedIds: [],
      // 复选框选中数据集合
      multipleSelection: [],
      // 表格数据
      tableData: [],
      tableKey: 0,
      list: null,
      total: 0,
      input1: '',
      input2: '',
      update_name: '',
      update_remark: ''
    }
  },
  watch: {
    user: {
      handler(user) {
        if (user) {
          console.log(user)
          this.form = { id: user.id, name: user.name, phoneNumber: user.phoneNumber, email: user.email, sex: user.sex, majorId: user.majorId }
        }
      },
      immediate: true
    }
  },
  created() {
    this.getDeptTree()
  },

  mounted() {
    this.page() // 当页面加载完成后，发送异步请求，获取数据
  },

  methods: {
    close() {
      this.$tab.closePage()
    },
    /** 查询部门下拉树结构 */
    getDeptTree() {
      deptTreeSelect().then(response => {
        this.deptOptions = response.data
      })
    },
    checkPermission,
    // 查询分页数据
    page() {
      // 初始化加载数据
      const requestData = {
        name: this.queryParams.name,
        current: this.current,
        pageSize: this.pageSize
      }

      page(requestData)
        .then((res) => {
          this.totalCount = res.data.total
          this.tableData = res.data.records
        })
        .catch((error) => {
          // 处理错误情况
          console.error('Error fetching data:', error)
        })
    },
    uploadChange(file, fileList) {
      console.log(file.name, fileList)
    },
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    handleExceed(files, fileList) {
      this.$message.error('上传文件超出限制')
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false
      this.fileName = response.data.fileName
      this.fileUrl = response.data.fileUrl
      this.fileList = [{
        name: response.data.fileName,
        url: response.data.fileUrl
      }]
      this.$message({ message: '上传成功', type: 'success' })
    },
    cancel() {
      this.dialogVisible = false
      this.fileList = []
    },
    handleAdd() {
      this.dialogVisible = true
      this.reset()
    },
    // 表单重置
    reset() {
      this.docu = {
        name: '',
        fileUrl: '',
        description: '',
        majorId: '',
        fileName: ''
      }
      this.majorData = {
        id: '',
        label: ''
      }
      this.majorList = []
      this.fileList = []
    },
    add() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 检查附件是否上传
          if (this.fileList.length === 0) {
            this.$message.error('请上传附件')
            return false
          }
          let operator
          if (this.docu.id) {
            // 修改
            operator = update(this.docu)
          } else {
            operator = add(this.docu)
          }
          operator.then((resp) => {
            if (resp.code === 1) {
              this.dialogVisible = false
              this.fileList = []
              this.page()
              this.$message({ message: '保存成功', type: 'success' })
            } else {
              this.$message.error(resp.msg)
            }
          })
        } else {
          return false
        }
      })
    },
    // 删除资料
    deleteById(id) {
      this.$confirm('此操作将删除该资料, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          // 2. 发送AJAX请求
          deleteById(id).then((resp) => {
            if (resp.code == 1) {
              // 删除成功
              this.$message.success('恭喜你，删除成功')
              this.page()
            } else {
              this.$message.error(resp.msg)
            }
          })
        })
        .catch(() => {
          // 用户点击取消按钮
          this.$message.info('已取消删除')
        })
    },
    handleDateChange(val) {
      if (val) {
        this.queryParams.createTime = val[0] // 开始时间
        this.queryParams.endTime = val[1] // 结束时间
      } else {
        this.queryParams.createTime = ''
        this.queryParams.endTime = ''
      }
    },
    // 复选框选中后执行的方法
    handleSelectionChange(val) {
      this.multipleSelection = val
    },

    // 查询方法
    onSubmit() {
      this.current = 1
      this.page()
    },
    // 重置方法
    clear() {
      this.queryParams.status = ''
      this.entryDate = [] // 清除时间范围
      this.queryParams.operName = ''
      this.queryParams.name = ''
      this.queryParams.majorId = ''
      this.queryParams.createTime = ''
      this.queryParams.endTime = ''
      this.page()
    },
    // 修改资料
    handleUpdate(id) {
      // 1. 打开窗口
      this.dialogVisible = true
      queryById(id).then((res) => {
        this.docu = res.data
        this.fileList.push({
          name: res.data.fileName,
          url: res.data.fileUrl
        })
      })
    },
    // 获取MajorName数据
    getMajorName(id) {
      deptTreeSelect(id).then((major) => {
        this.majorData = major.data
        this.majorList.push({
          id: major.data.id,
          majorName: major.data.label
        })
      })
    },
    // 分页
    handleSizeChange(val) {
      // 重新设置每页显示的条数
      this.pageSize = val
      this.page()
    },

    handleCurrentChange(val) {
      // 重新设置当前页码
      this.current = val
      this.page()
    },
    handleExport(row) {
      this.$confirm('是否下载文件?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          if (row.fileUrl) {
            const downloadUrl = row.fileUrl
            this.downloadFileByLink(downloadUrl)
          } else {
            this.$message.error('文件链接不存在')
          }
        })
        .catch(() => {
          this.$message.info('已取消下载')
        })
    },

    downloadFileByLink(url) {
      const fileName = url.substring(url.lastIndexOf('/') + 1)
      const a = document.createElement('a')
      a.href = url
      a.download = fileName
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
    }
  }
}
</script>

<style scoped>
/* 全局CSS 或者在<style scoped>内 */
.el-form-item .is-disabled .el-input__inner,
.is-disabled .el-date-editor.el-input__inner {
  background-color: #f5f7fa;
  /* 变更输入框背景色 */
  color: #c0c4cc;
  /* 变更文字颜色 */
  cursor: not-allowed;
  /* 更改鼠标指针形状 */
}

/* 如果需要单独针对学期学年（el-select）调整样式 */
.el-form-item .is-disabled .el-select .el-input__inner {
  /* 在这里添加特定于el-select的样式 */
}
</style>
